package shopping

import (
	"errors"
	"strings"
	//"strconv"
	"time"
	"dhfshop/utils/helper"
	"dhfshop/models"
	"dhfshop/models/misc"
	"dhfshop/models/consts"
	//"dhfshop/utils/math"
	"github.com/astaxie/beego/orm"
)

type PaymentList struct {
	PartnerId      int64      `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`                      /*分销商ID  */
	StoreId        int64      `orm:"column(store_id)" json:"store_id" form:"store_id"`                            /* 店铺ID */
	MemberId       int64      `orm:"column(member_id)" json:"member_id" form:"member_id"`                         /* 买家id */
	PaymentListId  string     `orm:"column(payment_list_id);size(64);pk" json:"payment_list_id" form:"payment_list_id"`   //支付单ID
	BusinessKind   int16      `orm:"column(business_kind)" json:"business_kind" form:"business_kind"`            /*业务类型: 1 订单支付 2 充值 3 退款*/
	OrderId        int64      `orm:"column(order_id);index" json:"order_id" form:"order_id"`                     /* 订单id */
	AccountTypeId  int        `orm:"column(account_type_id)" json:"account_type_id" form:"account_type_id"`      /* 账目类型: 1 入账 2 出账  */
	/* 账户信息 */
	OuterNo        string     `orm:"column(outer_no);size(64);index" json:"outer_no" form:"outer_no"`             /*支付网关的内部交易单号 */
	MchTypeId      int        `orm:"column(mch_type_id);default(1)" json:"mch_type_id" form:"mch_type_id"`        //商户类型: 1普通商户;2特约商户3个人收款码模式 
    AppId          string     `orm:"column(app_id);size(32);null" json:"app_id" form:"app_id"`                    //服务商ID
	MchId          string     `orm:"column(mch_id);size(32);null" json:"mch_id" form:"mch_id"`                    //微信商户号ID
	SubAppId       string     `orm:"column(sub_app_id);size(32);null" json:"sub_app_id" form:"sub_app_id"`        //小程序的APPID
	SubMchId       string     `orm:"column(sub_mch_id);size(32);null" json:"sub_mch_id" form:"sub_mch_id"`        //子商户号
	SellerBank     string     `orm:"column(seller_bank);size(64)" json:"seller_bank" form:"seller_bank"`          /*卖家收款银行 */
	SellerAccount  string     `orm:"column(seller_account);size(64)" json:"seller_account" form:"seller_account"` /*卖家收款帐号 */
	BuyerId        string     `orm:"column(buyer_id);size(64);index" json:"buyer_id" form:"buyer_id"`             /*买家会员ID */
	BuyerName      string     `orm:"column(buyer_name);size(64)" json:"buyer_name" form:"buyer_name"`             /*买家会员名 */
	BuyerBank      string     `orm:"column(buyer_bank);size(64)" json:"buyer_bank" form:"buyer_bank"`             /*买家付款银行 */
	BuyerAccount   string     `orm:"column(buyer_account);size(64)" json:"buyer_account" form:"buyer_account"`    /* 买家支付账户 */
	/* 财务信息 */
	PayTime        time.Time  `orm:"column(pay_time);type(datetime);null" json:"-" form:"-"`                     //支付时间
    PayTimeStr     string     `orm:"-" json:"pay_time" form:"pay_time"`                                          /* 输入输出 */
	PaymentCode    string     `orm:"column(payment_code);size(64);null" json:"payment_code" form:"payment_code"` /* 支付方式编码: 1 微信支付 2 余额支付 3 ROYAL支付 4 YahandPay 12 Usagms支付*/       
	PaymentName    string     `orm:"column(payment_name);size(64);null" json:"payment_name" form:"payment_name"` /* 支付方式名称 */
	PayFee         float32    `orm:"column(pay_fee);digits(12);decimals(2)" json:"pay_fee" form:"pay_fee"`         /* 本次支付金额*/
	CashFee        float32    `orm:"column(cash_fee);digits(12);decimals(2)" json:"cash_fee" form:"cash_fee"`      /*现金支付金额*/
	CouponFee      float32    `orm:"column(coupon_fee);digits(12);decimals(2)" json:"coupon_fee" form:"coupon_fee"` /*代金券或立减优惠金额*/
	PayCost        float32    `orm:"column(pay_cost);digits(12);decimals(2)" json:"pay_cost" form:"pay_cost"`    /*支付手续费*/
	/* 其它信息 */
	InvoiceNo      string     `orm:"column(invoice_no);size(128)" json:"invoice_no" form:"invoice_no"`                     /* 发票号 */
	Currency       string     `orm:"column(currency);size(50)" json:"currency" form:"currency"`        /*货币类型，可选：CNY:人民币,USD:美元,JPY:日元,默认CNY */
	Status         string     `orm:"column(status);size(32)" json:"status" form:"status"`                                  /* 状态 */
	SrcMessage     string     `orm:"column(src_message);type(text);null" json:"src_message" form:"src_message"`   /* 原始支付单信息  */
	Remark         string     `orm:"column(remark);size(128);null" json:"remark" form:"remark"`                   /* 备注  */
	CreatedAt      time.Time  `orm:"auto_now_add;column(created_at);type(datetime)" json:"-"`                     /* 单据创建时间 */
	CreatedAtStr   string     `orm:"-" json:"created_at"`
	UpdatedAt      time.Time  `orm:"auto_now;column(updated_at);type(datetime);null" json:"-"`	
	UpdatedAtStr   string     `orm:"-" json:"updated_at"`
	Kind           string     `orm:"column(kind);null" json:"kind" form:"kind"`  
	ProfitStatus   int        `orm:"column(profit_status);default(0)" json:"profit_status" form:"profit_status"` /*分账状态*/
}

func init() {
    orm.RegisterModel(new(PaymentList))   
}
					
func AddPaymentByPayMsg(partnerId,storeId,memberId,orderId int64,kind int16,
                        payCode,outerNo,currency,appId,mchId,listId,srcData string,
						payFee,cashFee,couponFee float32,mchTypeId int) (id string, err error) {
	o := models.GetDefaultDB()
	payment := new(PaymentList)
	if len(listId) > 3 {
	   payment.PaymentListId = listId
	}else{
	   payment.PaymentListId, _ = misc.GetBillNo("PA")
	}
	payment.PartnerId = partnerId
	payment.StoreId = storeId
	payment.MemberId = memberId
	payment.BusinessKind = kind
	payment.AccountTypeId = 0
	payment.BuyerId = ""
	payment.OrderId = orderId
	payment.OuterNo = outerNo
	if payCode == "1" {
		payment.AppId = appId
        payment.MchId = mchId		
		payment.MchTypeId = mchTypeId
	}
	payment.BuyerBank = ""       
	payment.PayTime = time.Now().UTC()
	payment.PaymentCode = payCode
	payment.PaymentName = ""
	payment.PayFee = payFee
	payment.CashFee = cashFee
	payment.CouponFee = couponFee
	payment.Currency = currency  
	payment.SrcMessage = srcData
	_, err = o.Insert(payment)
	id = payment.PaymentListId
	return
}

func GetPaymentListByMemberId(memberId int64) (v *PaymentList, err error) {
	o := models.GetDefaultDB()
	v = &PaymentList{MemberId: memberId}
	if err = o.Read(v, "MemberId"); err == nil {
		return v, nil
	}
	return nil, err
}

func GetPaymentListByOrderId(orderId int64) (v *PaymentList, err error) {
	o := models.GetDefaultDB()
	v = &PaymentList{OrderId: orderId}
	if err = o.Read(v, "OrderId"); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllPaymentLists(start,end string,query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*PaymentList,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(PaymentList))
	if len(start) == 19 {
	    if start_time, err := time.Parse(consts.DATETIME_FORMAT,start); err == nil {
		    qs = qs.Filter("created_at__gte", start_time)
		}
	}
	if len(end) == 19 {
	   if end_time, err := time.Parse(consts.DATETIME_FORMAT,end); err == nil {
	        qs = qs.Filter("created_at__lte", end_time)
	   }
	}
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*PaymentList
	has_order := false
	fieldsLen := len(fields)
	if fieldsLen == 0 {
	    has_order = true
	}else{
	    if has_order, err = helper.Contains("orders",fields); err == nil {
	        if has_order {
		        fields = helper.Remove(fields,"orders")
		    }
	    }
	}
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
	    for _, payment := range lists {
            payment.CreatedAtStr = payment.CreatedAt.Format(consts.DATETIME_FORMAT)
			payment.UpdatedAtStr = payment.UpdatedAt.Format(consts.DATETIME_FORMAT)
            payment.PayTimeStr = payment.PayTime.Format(consts.DATETIME_FORMAT)
			//payment.TypeId = payment.Type.TypeId
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func updatePaymentlist(m *PaymentList, param ...string) (err error) {
	o := models.GetDefaultDB()
	v := PaymentList{PaymentListId: m.PaymentListId}
	if err = o.Read(&v); err == nil {
		_, err = o.Update(m, param...)
		return
	}
	return
}

//更新支付单分账信息
func UpdatePaymentProfit(m *PaymentList) (err error) {
	err = updatePaymentlist(m, "profit_status")
	return
}

func SumPaymentByTid(companyId int,tid int64) (totalPay float32, err error) {
	sql := "select sum(pay_fee) as total from payment_list where company_id = ? and tid = ?"
       o := models.GetDefaultDB()
	err = o.Raw(sql, companyId, tid).QueryRow(&totalPay)
	return
}

